// 初始化 Cesium Viewer

import * as Cesium from "cesium";

export default class TerrainExcavation2{
  // 定义要开挖的区域，使用经纬度坐标（纬度, 经度, 高度）
  positions = [
    Cesium.Cartesian3.fromDegrees(-115.0, 37.0, 1000.0),
    Cesium.Cartesian3.fromDegrees(-115.0, 36.0, 1000.0),
    Cesium.Cartesian3.fromDegrees(-114.0, 36.0, 1000.0),
    Cesium.Cartesian3.fromDegrees(-114.0, 37.0, 1000.0)
  ];
  // 创建裁剪平面集合
  clippingPlanes = [];

  viewer;

  constructor(viewer) {
    this.viewer=viewer;
    for (var i = 0; i < this.positions.length; i++) {
      var nextIndex = (i + 1) % this.positions.length;

      // 计算当前点与下一个点之间的法向量
      var midpoint = Cesium.Cartesian3.add(this.positions[i], this.positions[nextIndex], new Cesium.Cartesian3());
      midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);

      var up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
      var right = Cesium.Cartesian3.subtract(this.positions[nextIndex], midpoint, new Cesium.Cartesian3());
      right = Cesium.Cartesian3.normalize(right, right);

      var normal = Cesium.Cartesian3.cross(right, up, new Cesium.Cartesian3());
      normal = Cesium.Cartesian3.normalize(normal, normal);

      var originCenteredPlane = new Cesium.Plane(normal, 0.0);
      var distance = Cesium.Plane.getPointDistance(originCenteredPlane, midpoint);

      // 创建裁剪平面
      this.clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
    }

    // 应用裁剪平面到地形上
    this.viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
      planes: this.clippingPlanes,
      edgeWidth: 1.0,
      edgeColor: Cesium.Color.WHITE,
      enabled: true // 启用裁剪平面
    });

    // 调用添加墙壁函数
    this.addWalls();
  }
  // 为了增强视觉效果，可以给开挖的区域添加墙壁或底部
  addWalls() {
    this.viewer.entities.add({
      wall: {
        positions: this.positions,
        maximumHeights: this.positions.map(function () {
          return 1000;
        }),
        minimumHeights: this.positions.map(function () {
          return 0;
        }),
        material: Cesium.Color.GRAY.withAlpha(0.5)
      }
    });
  }

}

